<template>
  <div id="app">
    <uploader :options="options"
                @file-added="onFileAdded"
                @file-success="onFileSuccess"
     class="uploader-example">
    <uploader-unsupport></uploader-unsupport>
    <uploader-drop>
      <p>Drop files here to upload or</p>
      <uploader-btn>select files</uploader-btn>
      <!--<uploader-btn :directory="true">select folder</uploader-btn>-->
    </uploader-drop>
    <uploader-list></uploader-list>
  </uploader>
  </div>
</template>

<script>
import  SparkMD5 from "spark-md5"

export default {
 data () {
      return {
        options: {
          target: '/upload', //目标上传地址
          testChunks: true, //分片上传前发送chunk check GET请求,如果文件已经存在则返回isExist，如果已上传了部分分片则返回分片的chunkNumber
          checkChunkUploadedByResponse: (chunk, message) => {
              let obj = JSON.parse(message);
              if (obj.data.isExist) {
                  return true;
              }
              return (obj.data.uploaded || []).indexOf(chunk.offset + 1) >= 0
          },
          chunkSize: 1024*1024*2,  //2MB
          simultaneousUploads: 3, //并发上传数
          fileParameterName: "file", //上传文件时文件的参数名
          maxChunkRetries: 3, //最大自动失败重试上传次数
          autoStart:true,//是否选择文件时会响应几种状态
          fileStatusText:{ //文件在上传时会响应几种状态
             success: 'success11',
             error: 'error',
             uploading: 'uploading',
             paused: 'paused',
             waiting: 'waiting',
             cmd5: 'preprocessing...'
          }
        },
        attrs: {
          accept: '*'
        }
      }
    },
    methods: {
      onFileAdded(file) {
        //文件添加的时候暂停文件的上传，计算md5值
        file.pause();
        // 计算MD5值,作为文件的唯一标识
        this.computeMD5(file);
      },
      computeMD5(file) {
        let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
        chunkSize = 1024*1024*2, //2MB
        chunks = Math.ceil(file.size / chunkSize),
        currentChunk = 0,
        spark = new SparkMD5.ArrayBuffer(),
        fileReader = new FileReader();
        let time = new Date().getTime();
        file.cmd5 = true; //文件状态为“计算md5...”
        fileReader.onload = (e) => {
            spark.append(e.target.result);   // Append array buffer
            currentChunk++;
            if (currentChunk < chunks) {
                console.log(`第${currentChunk}分片解析完成, 开始第${currentChunk +1} / ${chunks}分片解析`);
                loadNext();
            } else {
                console.log('finished loading');
                //得到md5
                var md5 = spark.end(); 
                console.log(`MD5计算完成：${file.name} \nMD5：${md5} \n分片：${chunks} 大小:${file.size} 用时：${new Date().getTime() - time} ms`);
                //释放缓存
                spark.destroy(); 
                //将文件md5赋值给文件唯一标识
                file.uniqueIdentifier = md5; 
                //取消计算md5状态
                file.cmd5 = false; 
                //console.log(JSON.stringify(file))
                //恢复文件的上传
                file.resume(); 
            }
        };
        fileReader.onerror = () => {
            console.warn('oops, something went wrong.');
            file.cancel();
        };
        let loadNext = () =>　{
            let start = currentChunk * chunkSize,
            end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
            fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
        };
        loadNext();
      },
      //分片全部上传完成触发
      onFileSuccess(rootFile, file, response, chunk) { 
          var obj = JSON.parse(response);
          console.log(JSON.stringify(response))
          //console.log(JSON.stringify(file))
          if(obj.data.merge){
            console.log("文件需要合并操作")
            this.axios.post('/merge',{
                identifier: file.uniqueIdentifier,
                filename: file.name,
                totalChunks: chunk.offset + 1
            }).then(function(res){
                if (res.code === 0) {
                    console.log('上传成功')
                } else {
                    console.log(res.data.message);
                }
            })
            .catch(function(error){
                console.log(error);
            });
          }else{
            console.log("文件上传成功")
          }
        },
    }
}
</script>

<style>
 .uploader-example {
    width: 880px;
    padding: 15px;
    margin: 40px auto 0;
    font-size: 12px;
    box-shadow: 0 0 10px rgba(0, 0, 0, .4);
  }
  .uploader-example .uploader-btn {
    margin-right: 4px;
  }
  .uploader-example .uploader-list {
    max-height: 440px;
    overflow: auto;
    overflow-x: hidden;
    overflow-y: auto;
  }
</style>
